Project: Identify Customer Segments

In this project, you will apply unsupervised learning techniques to identify segments of the population that form the core customer base for a mail-order sales company in Germany. These segments can then be used to direct marketing campaigns towards audiences that will have the highest expected rate of returns. The data that you will use has been provided by our partners at Bertelsmann Arvato Analytics, and represents a real-life data science task.

This notebook will help you complete this task by providing a framework within which you will perform your analysis steps. In each step of the project, you will see some text describing the subtask that you will perform, followed by one or more code cells for you to complete your work. Feel free to add additional code and markdown cells as you go along so that you can explore everything in precise chunks. The code cells provided in the base template will outline only the major tasks, and will usually not be enough to cover all of the minor tasks that comprise it.

It should be noted that while there will be precise guidelines on how you should handle certain tasks in the project, there will also be places where an exact specification is not provided. There will be times in the project where you will need to make and justify your own decisions on how to treat the data. These are places where there may not be only one way to handle the data. In real-life tasks, there may be many valid ways to approach an analysis task. One of the most important things you can do is clearly document your approach so that other scientists can understand the decisions you've made.

At the end of most sections, there will be a Markdown cell labeled Discussion. In these cells, you will report your findings for the completed section, as well as document the decisions that you made in your approach to each subtask. Your project will be evaluated not just on the code used to complete the tasks outlined, but also your communication about your observations and conclusions at each stage.

In [1]:
# import libraries here; add more as necessary
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import re

from IPython.display import display

# magic word for producing visualizations in notebook
%matplotlib inline
%config InlineBackend.figure_format = 'retina'

Step 0: Load the Data

There are four files associated with this project (not including this one):

  • Udacity_AZDIAS_Subset.csv: Demographics data for the general population of Germany; 891211 persons (rows) x 85 features (columns).
  • Udacity_CUSTOMERS_Subset.csv: Demographics data for customers of a mail-order company; 191652 persons (rows) x 85 features (columns).
  • Data_Dictionary.md: Detailed information file about the features in the provided datasets.
  • AZDIAS_Feature_Summary.csv: Summary of feature attributes for demographics data; 85 features (rows) x 4 columns

Each row of the demographics files represents a single person, but also includes information outside of individuals, including information about their household, building, and neighborhood. You will use this information to cluster the general population into groups with similar demographic properties. Then, you will see how the people in the customers dataset fit into those created clusters. The hope here is that certain clusters are over-represented in the customers data, as compared to the general population; those over-represented clusters will be assumed to be part of the core userbase. This information can then be used for further applications, such as targeting for a marketing campaign.

To start off with, load in the demographics data for the general population into a pandas DataFrame, and do the same for the feature attributes summary. Note for all of the .csv data files in this project: they're semicolon (;) delimited, so you'll need an additional argument in your read_csv() call to read in the data properly. Also, considering the size of the main dataset, it may take some time for it to load completely.

Once the dataset is loaded, it's recommended that you take a little bit of time just browsing the general structure of the dataset and feature summary file. You'll be getting deep into the innards of the cleaning in the first major step of the project, so gaining some general familiarity can help you get your bearings.

In [2]:
# Load in the general demographics data.
azdias = pd.read_csv('Udacity_AZDIAS_Subset.csv', delimiter=';')

# Load in the feature summary file.
feat_info = pd.read_csv('AZDIAS_Feature_Summary.csv', delimiter=';')
In [3]:
# Check the structure of the data after it's loaded (e.g. print the number of
# rows and columns, print the first few rows).

azdias.shape
Out[3]:
(891221, 85)
In [4]:
azdias.head(3)
Out[4]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 -1 2 1 2.0 3 4 3 5 5 3 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
1 -1 1 2 5.0 1 5 2 5 4 5 ... 2.0 3.0 2.0 1.0 1.0 5.0 4.0 3.0 5.0 4.0
2 -1 3 2 3.0 1 4 1 2 3 5 ... 3.0 3.0 1.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0

3 rows × 85 columns

In [5]:
azdias.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891221 entries, 0 to 891220
Data columns (total 85 columns):
AGER_TYP                 891221 non-null int64
ALTERSKATEGORIE_GROB     891221 non-null int64
ANREDE_KZ                891221 non-null int64
CJT_GESAMTTYP            886367 non-null float64
FINANZ_MINIMALIST        891221 non-null int64
FINANZ_SPARER            891221 non-null int64
FINANZ_VORSORGER         891221 non-null int64
FINANZ_ANLEGER           891221 non-null int64
FINANZ_UNAUFFAELLIGER    891221 non-null int64
FINANZ_HAUSBAUER         891221 non-null int64
FINANZTYP                891221 non-null int64
GEBURTSJAHR              891221 non-null int64
GFK_URLAUBERTYP          886367 non-null float64
GREEN_AVANTGARDE         891221 non-null int64
HEALTH_TYP               891221 non-null int64
LP_LEBENSPHASE_FEIN      886367 non-null float64
LP_LEBENSPHASE_GROB      886367 non-null float64
LP_FAMILIE_FEIN          886367 non-null float64
LP_FAMILIE_GROB          886367 non-null float64
LP_STATUS_FEIN           886367 non-null float64
LP_STATUS_GROB           886367 non-null float64
NATIONALITAET_KZ         891221 non-null int64
PRAEGENDE_JUGENDJAHRE    891221 non-null int64
RETOURTYP_BK_S           886367 non-null float64
SEMIO_SOZ                891221 non-null int64
SEMIO_FAM                891221 non-null int64
SEMIO_REL                891221 non-null int64
SEMIO_MAT                891221 non-null int64
SEMIO_VERT               891221 non-null int64
SEMIO_LUST               891221 non-null int64
SEMIO_ERL                891221 non-null int64
SEMIO_KULT               891221 non-null int64
SEMIO_RAT                891221 non-null int64
SEMIO_KRIT               891221 non-null int64
SEMIO_DOM                891221 non-null int64
SEMIO_KAEM               891221 non-null int64
SEMIO_PFLICHT            891221 non-null int64
SEMIO_TRADV              891221 non-null int64
SHOPPER_TYP              891221 non-null int64
SOHO_KZ                  817722 non-null float64
TITEL_KZ                 817722 non-null float64
VERS_TYP                 891221 non-null int64
ZABEOTYP                 891221 non-null int64
ALTER_HH                 817722 non-null float64
ANZ_PERSONEN             817722 non-null float64
ANZ_TITEL                817722 non-null float64
HH_EINKOMMEN_SCORE       872873 non-null float64
KK_KUNDENTYP             306609 non-null float64
W_KEIT_KIND_HH           783619 non-null float64
WOHNDAUER_2008           817722 non-null float64
ANZ_HAUSHALTE_AKTIV      798073 non-null float64
ANZ_HH_TITEL             794213 non-null float64
GEBAEUDETYP              798073 non-null float64
KONSUMNAEHE              817252 non-null float64
MIN_GEBAEUDEJAHR         798073 non-null float64
OST_WEST_KZ              798073 non-null object
WOHNLAGE                 798073 non-null float64
CAMEO_DEUG_2015          792242 non-null object
CAMEO_DEU_2015           792242 non-null object
CAMEO_INTL_2015          792242 non-null object
KBA05_ANTG1              757897 non-null float64
KBA05_ANTG2              757897 non-null float64
KBA05_ANTG3              757897 non-null float64
KBA05_ANTG4              757897 non-null float64
KBA05_BAUMAX             757897 non-null float64
KBA05_GBZ                757897 non-null float64
BALLRAUM                 797481 non-null float64
EWDICHTE                 797481 non-null float64
INNENSTADT               797481 non-null float64
GEBAEUDETYP_RASTER       798066 non-null float64
KKK                      770025 non-null float64
MOBI_REGIO               757897 non-null float64
ONLINE_AFFINITAET        886367 non-null float64
REGIOTYP                 770025 non-null float64
KBA13_ANZAHL_PKW         785421 non-null float64
PLZ8_ANTG1               774706 non-null float64
PLZ8_ANTG2               774706 non-null float64
PLZ8_ANTG3               774706 non-null float64
PLZ8_ANTG4               774706 non-null float64
PLZ8_BAUMAX              774706 non-null float64
PLZ8_HHZ                 774706 non-null float64
PLZ8_GBZ                 774706 non-null float64
ARBEIT                   794005 non-null float64
ORTSGR_KLS9              794005 non-null float64
RELAT_AB                 794005 non-null float64
dtypes: float64(49), int64(32), object(4)
memory usage: 578.0+ MB

Tip: Add additional cells to keep everything in reasonably-sized chunks! Keyboard shortcut esc --> a (press escape to enter command mode, then press the 'A' key) adds a new cell before the active cell, and esc --> b adds a new cell after the active cell. If you need to convert an active cell to a markdown cell, use esc --> m and to convert to a code cell, use esc --> y.

Step 1: Preprocessing

Step 1.1: Assess Missing Data

The feature summary file contains a summary of properties for each demographics data column. You will use this file to help you make cleaning decisions during this stage of the project. First of all, you should assess the demographics data in terms of missing data. Pay attention to the following points as you perform your analysis, and take notes on what you observe. Make sure that you fill in the Discussion cell with your findings and decisions at the end of each step that has one!

Step 1.1.1: Convert Missing Value Codes to NaNs

The fourth column of the feature attributes summary (loaded in above as feat_info) documents the codes from the data dictionary that indicate missing or unknown data. While the file encodes this as a list (e.g. [-1,0]), this will get read in as a string object. You'll need to do a little bit of parsing to make use of it to identify and clean the data. Convert data that matches a 'missing' or 'unknown' value code into a numpy NaN value. You might want to see how much data takes on a 'missing' or 'unknown' code, and how much data is naturally missing, as a point of interest.

As one more reminder, you are encouraged to add additional cells to break up your analysis into manageable chunks.

In [6]:
print('feat_info shape:', feat_info.shape)
print('\nfeat_info head:')
display(feat_info.head())
print('\nInformation Levels:')
display(feat_info.information_level.unique())
print('\nTypes:')
display(feat_info['type'].unique())
print('\nMissing or Unknown Values')
display(feat_info.missing_or_unknown.unique())
feat_info shape: (85, 4)

feat_info head:
attribute information_level type missing_or_unknown
0 AGER_TYP person categorical [-1,0]
1 ALTERSKATEGORIE_GROB person ordinal [-1,0,9]
2 ANREDE_KZ person categorical [-1,0]
3 CJT_GESAMTTYP person categorical [0]
4 FINANZ_MINIMALIST person ordinal [-1]
Information Levels:
array(['person', 'household', 'building', 'microcell_rr4', 'microcell_rr3',
       'postcode', 'region_rr1', 'macrocell_plz8', 'community'], dtype=object)
Types:
array(['categorical', 'ordinal', 'numeric', 'mixed', 'interval'], dtype=object)
Missing or Unknown Values
array(['[-1,0]', '[-1,0,9]', '[0]', '[-1]', '[]', '[-1,9]', '[-1,X]',
       '[XX]', '[-1,XX]'], dtype=object)
In [7]:
azdias.isnull().sum().sum()
Out[7]:
4896838
In [8]:
# Identify missing or unknown data values and convert them to NaNs.

def convert_missing_unknown_to_nan(df, features=feat_info):
    """
    Identify missing or unknown data values in the data frame df and convert them to NaNs.
    Arg: data frames df and features
    Returns: converted data frame
    """
    unknown_or_missing_vals = list(set(features.missing_or_unknown.unique()) - set(['[]']))
    #print(unknown_or_missing_vals)
    regex = re.compile(r'[-]?\d|[X]+')
    for val in unknown_or_missing_vals:
        if val == '[XX]':
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace(['XX'], np.nan)

        elif val == '[-1,X]':
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace([-1, 'X'], np.nan)

        elif val == '[-1,XX]':
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace([-1, 'XX'], np.nan)

        else:
            unknown_num_vals = regex.findall(val)
            unknown_num_vals = list(map(int, unknown_num_vals))
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace(unknown_num_vals, np.nan)
            
    return df
            
In [9]:
# Apply the convert_missing_unknown_to_nan function to the azdias dataframe
azdias = convert_missing_unknown_to_nan(azdias)
In [10]:
azdias.isnull().sum().sum()
Out[10]:
8373929

Step 1.1.2: Assess Missing Data in Each Column

How much missing data is present in each column? There are a few columns that are outliers in terms of the proportion of values that are missing. You will want to use matplotlib's hist() function to visualize the distribution of missing value counts to find these columns. Identify and document these columns. While some of these columns might have justifications for keeping or re-encoding the data, for this project you should just remove them from the dataframe. (Feel free to make remarks about these outlier columns in the discussion, however!)

For the remaining features, are there any patterns in which columns have, or share, missing data?

In [11]:
# Perform an assessment of how much missing data there is in each column of the
# dataset.
azdias.isnull().sum().hist(bins=15)
plt.xlabel('Number of Missing/unknown values')
plt.ylabel('Frequency');
In [12]:
# Investigate patterns in the amount of missing data in each column.
plt.figure(figsize=(12, 26))
ax = azdias.isnull().sum().sort_values().plot(kind='barh')
plt.axvline(x=200000, ls='-.', color='red');
In [13]:
# Features with more than 200000 missing values
remove_feats = list(azdias.columns[azdias.isnull().sum().values > 200000])
remove_feats
Out[13]:
['AGER_TYP',
 'GEBURTSJAHR',
 'TITEL_KZ',
 'ALTER_HH',
 'KK_KUNDENTYP',
 'KBA05_BAUMAX']
In [14]:
# Remove the outlier columns from the dataset. (You'll perform other data
# engineering tasks such as re-encoding and imputation later.)

azdias.drop(remove_feats, axis=1, inplace=True)
In [15]:
plt.figure(figsize=(12, 22))
azdias.isnull().sum().sort_values().plot(kind='barh')
plt.axvline(x=200000, ls='-.', color='red');

Discussion 1.1.2: Assess Missing Data in Each Column

There appears to be patterns in the number of missing values, and it generally depends on the information level of features. The "FINANZ" and "SEMIO" features are both complete, with no missing values. The columns with more than 200000 missing values that were removed from the dataset are: "AGER_TYP", "GEBURTSJAHR", "TITEL_KZ", "ALTER_HH", "KK_KUNDENTYP", and "KBA05_BAUMAX".

Step 1.1.3: Assess Missing Data in Each Row

Now, you'll perform a similar assessment for the rows of the dataset. How much data is missing in each row? As with the columns, you should see some groups of points that have a very different numbers of missing values. Divide the data into two subsets: one for data points that are above some threshold for missing values, and a second subset for points below that threshold.

In order to know what to do with the outlier rows, we should see if the distribution of data values on columns that are not missing data (or are missing very little data) are similar or different between the two groups. Select at least five of these columns and compare the distribution of values.

  • You can use seaborn's countplot() function to create a bar chart of code frequencies and matplotlib's subplot() function to put bar charts for the two subplots side by side.
  • To reduce repeated code, you might want to write a function that can perform this comparison, taking as one of its arguments a column to be compared.

Depending on what you observe in your comparison, this will have implications on how you approach your conclusions later in the analysis. If the distributions of non-missing features look similar between the data with many missing values and the data with few or no missing values, then we could argue that simply dropping those points from the analysis won't present a major issue. On the other hand, if the data with many missing values looks very different from the data with few or no missing values, then we should make a note on those data as special. We'll revisit these data later on. Either way, you should continue your analysis for now using just the subset of the data with few or no missing values.

In [16]:
# Distribution of row-total missing values 
azdias.isnull().sum(axis=1).hist();
In [17]:
# Rows with the highest row-total missing values
azdias.isnull().sum(axis=1).sort_values()[-10:]
Out[17]:
139332    47
691183    47
691171    47
691142    47
691141    47
139316    47
183108    47
472919    48
732775    49
643174    49
dtype: int64
In [18]:
azdias.iloc[azdias.isnull().sum(axis=1).sort_values()[-3:].index]
Out[18]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
472919 1.0 1 NaN 5 1 5 2 3 2 2 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
732775 3.0 2 NaN 3 5 3 5 5 2 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
643174 3.0 1 NaN 2 5 3 5 5 2 4 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

3 rows × 79 columns

In [19]:
# Rows with the lowest row-total missing values
azdias.isnull().sum(axis=1).sort_values()[:10]
Out[19]:
445610    0
540274    0
540275    0
540277    0
540280    0
540281    0
540283    0
540284    0
540286    0
540273    0
dtype: int64
In [20]:
azdias.iloc[azdias.isnull().sum(axis=1).sort_values()[:3].index]
Out[20]:
ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER FINANZTYP ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
445610 4.0 2 2.0 5 1 5 2 1 3 2 ... 4.0 1.0 0.0 0.0 1.0 4.0 5.0 2.0 1.0 1.0
540274 4.0 2 6.0 5 1 5 1 1 2 2 ... 4.0 2.0 0.0 0.0 1.0 3.0 4.0 3.0 7.0 3.0
540275 3.0 2 4.0 5 2 4 3 3 1 6 ... 4.0 2.0 0.0 0.0 1.0 4.0 4.0 3.0 5.0 2.0

3 rows × 79 columns

In [21]:
azdias.isnull().sum().sort_values()[:6]
Out[21]:
ZABEOTYP      0
SEMIO_REL     0
SEMIO_MAT     0
SEMIO_VERT    0
SEMIO_LUST    0
SEMIO_ERL     0
dtype: int64
In [22]:
# Six columns with zero missing values used to compare the distributions of 
# values in the two groups below, obtained by dividing the azdias dataset based on
# the row-total missing values being more or at most equal to the threshold value of 25
dense_feats = azdias.isnull().sum().sort_values().keys()[:6]
dense_feats
Out[22]:
Index(['ZABEOTYP', 'SEMIO_REL', 'SEMIO_MAT', 'SEMIO_VERT', 'SEMIO_LUST',
       'SEMIO_ERL'],
      dtype='object')
In [23]:
azdias.ZABEOTYP.unique()
Out[23]:
array([3, 5, 4, 1, 6, 2])
In [24]:
# Dividing the azdias dataset into two groups - 
# one with row-total missing values at most 25 and another one with
# higher than 25
ind_below_trsh = azdias.isnull().sum(axis=1).values <=25

azdias_below_trsh = azdias.iloc[ind_below_trsh]
azdias_above_trsh = azdias.iloc[~ind_below_trsh]
In [25]:
# Proportions of the two groups relative to the original azdias dataset
prop_below = azdias_below_trsh.shape[0] / azdias.shape[0]
prop_above = azdias_above_trsh.shape[0] / azdias.shape[0]
print(prop_below, prop_above)
0.8953570438757614 0.10464295612423855

Note: about 89.5% of the original dataset are in azdias_below_trsh subset and about 10.5% of the original dataset are in the azdias_above_trsh subset.

In [26]:
# Compare the distribution of values for at least five columns where there are
# no or few missing values, between the two subsets.
def comparison_plot(vars):
    n = len(vars)
    for i in range(n):
        plt.figure(figsize=(12, 3))
        plt.subplot(1, 2, 1)
        ax=sns.countplot(x=vars[i], data=azdias_above_trsh, palette='Oranges_r')
        ax.set_xlabel('{} ({})'.format(vars[i], 'Above Threshold'), color='#e74c3c', size=12)
        plt.subplot(1, 2, 2)
        ax=sns.countplot(x=vars[i], data=azdias_below_trsh, palette='GnBu_d')
        ax.set_xlabel('{} ({})'.format(vars[i], 'Below Threshold'), color='#3498db', size=12)

        plt.tight_layout()
    
In [27]:
comparison_plot(dense_feats)

Discussion 1.1.3: Assess Missing Data in Each Row

The above plots show that the data with lots of missing values in their rows (azdias_above_trsh) are qualitatively different from the data with few or no missing values in their rows (azdias_below_trsh). Alternatively, we can also use a Kolmogorov-Smirnov test to test each column against the null hypothesis. The lower the p-value the more we can assume that the two distributions are different.

In [28]:
from scipy.stats import ks_2samp
comp_df = pd.DataFrame(azdias.columns, columns=['col'])
def hypothesis_test(df1, df2, cols):
    stats = []
    pvalues = []
    for col in cols:
        counts_main = df1[col].value_counts().sort_index()
        counts_drop = df2[col].value_counts().sort_index()
        try:
            ch = ks_2samp(counts_main, counts_drop)
            stats.append(ch.statistic)
            pvalues.append(ch.pvalue)
        except:
            stats.append(np.nan)
            pvalues.append(np.nan)

    return stats, pvalues

stats, pvalues = hypothesis_test(azdias_below_trsh, azdias_above_trsh, azdias_below_trsh.columns.values)
comp_df['stats'] = stats
comp_df['pvalues'] = pvalues
comp_df.head()
/opt/conda/lib/python3.6/site-packages/scipy/stats/stats.py:4751: RuntimeWarning: invalid value encountered in true_divide
  cdf2 = np.searchsorted(data2, data_all, side='right') / (1.0*n2)
/opt/conda/lib/python3.6/site-packages/scipy/stats/stats.py:4756: RuntimeWarning: divide by zero encountered in double_scalars
  prob = distributions.kstwobign.sf((en + 0.12 + 0.11 / en) * d)
Out[28]:
col stats pvalues
0 ALTERSKATEGORIE_GROB 1.0 0.011066
1 ANREDE_KZ 1.0 0.097027
2 CJT_GESAMTTYP 1.0 0.001300
3 FINANZ_MINIMALIST 1.0 0.003781
4 FINANZ_SPARER 1.0 0.003781

Thanks to the first reviewer for suggesting the hypothesis-test method above and the seaborn distplots below!

In [29]:
plt.figure(figsize=(100,100))
for i, col in enumerate(azdias.columns[:10]):
    plt.subplot(5, 2, i+1)
    sns.distplot(azdias_below_trsh[col][azdias_below_trsh[col].notnull()], label='below')
    sns.distplot(azdias_above_trsh[col][azdias_above_trsh[col].notnull()], label='above')
    plt.title('Distribution for column: {}'.format(col))
    plt.legend();

Step 1.2: Select and Re-Encode Features

Checking for missing data isn't the only way in which you can prepare a dataset for analysis. Since the unsupervised learning techniques to be used will only work on data that is encoded numerically, you need to make a few encoding changes or additional assumptions to be able to make progress. In addition, while almost all of the values in the dataset are encoded using numbers, not all of them represent numeric values. Check the third column of the feature summary (feat_info) for a summary of types of measurement.

  • For numeric and interval data, these features can be kept without changes.
  • Most of the variables in the dataset are ordinal in nature. While ordinal values may technically be non-linear in spacing, make the simplifying assumption that the ordinal variables can be treated as being interval in nature (that is, kept without any changes).
  • Special handling may be necessary for the remaining two variable types: categorical, and 'mixed'.

In the first two parts of this sub-step, you will perform an investigation of the categorical and mixed-type features and make a decision on each of them, whether you will keep, drop, or re-encode each. Then, in the last part, you will create a new data frame with only the selected and engineered columns.

Data wrangling is often the trickiest part of the data analysis process, and there's a lot of it to be done here. But stick with it: once you're done with this step, you'll be ready to get to the machine learning parts of the project!

In [30]:
# How many features are there of each data type?

feat_info.type.value_counts()
Out[30]:
ordinal        49
categorical    21
mixed           7
numeric         7
interval        1
Name: type, dtype: int64

Step 1.2.1: Re-Encode Categorical Features

For categorical data, you would ordinarily need to encode the levels as dummy variables. Depending on the number of categories, perform one of the following:

  • For binary (two-level) categoricals that take numeric values, you can keep them without needing to do anything.
  • There is one binary variable that takes on non-numeric values. For this one, you need to re-encode the values as numbers or create a dummy variable.
  • For multi-level categoricals (three or more values), you can choose to encode the values using multiple dummy variables (e.g. via OneHotEncoder), or (to keep things straightforward) just drop them from the analysis. As always, document your choices in the Discussion section.
In [31]:
feat_info[feat_info.type == 'categorical']
Out[31]:
attribute information_level type missing_or_unknown
0 AGER_TYP person categorical [-1,0]
2 ANREDE_KZ person categorical [-1,0]
3 CJT_GESAMTTYP person categorical [0]
10 FINANZTYP person categorical [-1]
12 GFK_URLAUBERTYP person categorical []
13 GREEN_AVANTGARDE person categorical []
17 LP_FAMILIE_FEIN person categorical [0]
18 LP_FAMILIE_GROB person categorical [0]
19 LP_STATUS_FEIN person categorical [0]
20 LP_STATUS_GROB person categorical [0]
21 NATIONALITAET_KZ person categorical [-1,0]
38 SHOPPER_TYP person categorical [-1]
39 SOHO_KZ person categorical [-1]
40 TITEL_KZ person categorical [-1,0]
41 VERS_TYP person categorical [-1]
42 ZABEOTYP person categorical [-1,9]
47 KK_KUNDENTYP household categorical [-1]
52 GEBAEUDETYP building categorical [-1,0]
55 OST_WEST_KZ building categorical [-1]
57 CAMEO_DEUG_2015 microcell_rr4 categorical [-1,X]
58 CAMEO_DEU_2015 microcell_rr4 categorical [XX]
In [32]:
# The categorical features less the features that were already removed in step 1.1.2
cat_feats = list(set(feat_info[feat_info.type == 'categorical'].attribute.values )-set(remove_feats))

cat_feats
Out[32]:
['CJT_GESAMTTYP',
 'LP_STATUS_FEIN',
 'SHOPPER_TYP',
 'ZABEOTYP',
 'FINANZTYP',
 'LP_FAMILIE_FEIN',
 'CAMEO_DEU_2015',
 'CAMEO_DEUG_2015',
 'ANREDE_KZ',
 'SOHO_KZ',
 'LP_FAMILIE_GROB',
 'GFK_URLAUBERTYP',
 'NATIONALITAET_KZ',
 'GREEN_AVANTGARDE',
 'OST_WEST_KZ',
 'LP_STATUS_GROB',
 'GEBAEUDETYP',
 'VERS_TYP']
In [33]:
df_cat = azdias_below_trsh[cat_feats]
In [34]:
df_cat.head()
Out[34]:
CJT_GESAMTTYP LP_STATUS_FEIN SHOPPER_TYP ZABEOTYP FINANZTYP LP_FAMILIE_FEIN CAMEO_DEU_2015 CAMEO_DEUG_2015 ANREDE_KZ SOHO_KZ LP_FAMILIE_GROB GFK_URLAUBERTYP NATIONALITAET_KZ GREEN_AVANTGARDE OST_WEST_KZ LP_STATUS_GROB GEBAEUDETYP VERS_TYP
1 5.0 2.0 3.0 5 1 5.0 8A 8 2 1.0 3.0 10.0 1.0 0 W 1.0 8.0 2.0
2 3.0 3.0 2.0 5 1 1.0 4C 4 2 0.0 1.0 10.0 1.0 1 W 2.0 1.0 1.0
3 2.0 9.0 1.0 3 6 NaN 2A 2 2 0.0 NaN 1.0 1.0 0 W 4.0 1.0 1.0
4 5.0 3.0 2.0 4 5 10.0 6B 6 1 0.0 5.0 5.0 1.0 0 W 2.0 1.0 2.0
5 2.0 4.0 0.0 4 2 1.0 8C 8 2 0.0 1.0 1.0 1.0 0 W 2.0 1.0 2.0
In [35]:
# Assess categorical variables: which are binary, which are multi-level, and
# which one needs to be re-encoded?
df_cat.nunique()
Out[35]:
CJT_GESAMTTYP        6
LP_STATUS_FEIN      10
SHOPPER_TYP          4
ZABEOTYP             6
FINANZTYP            6
LP_FAMILIE_FEIN     11
CAMEO_DEU_2015      44
CAMEO_DEUG_2015      9
ANREDE_KZ            2
SOHO_KZ              2
LP_FAMILIE_GROB      5
GFK_URLAUBERTYP     12
NATIONALITAET_KZ     3
GREEN_AVANTGARDE     2
OST_WEST_KZ          2
LP_STATUS_GROB       5
GEBAEUDETYP          7
VERS_TYP             2
dtype: int64
In [36]:
# The binary categorical features will be kept and the multi-level categoricals (three or more values)
# will be dropped
retain_cat_feats = list(df_cat.nunique()[df_cat.nunique().values < 3].keys())
drop_cat_feats = list(set(cat_feats) - set(retain_cat_feats))
In [37]:
df_cat[retain_cat_feats].nunique()
Out[37]:
ANREDE_KZ           2
SOHO_KZ             2
GREEN_AVANTGARDE    2
OST_WEST_KZ         2
VERS_TYP            2
dtype: int64

Note: the feature OST_WEST_KZ has non-numeric values.

In [38]:
display(drop_cat_feats)
['CJT_GESAMTTYP',
 'ZABEOTYP',
 'LP_STATUS_FEIN',
 'SHOPPER_TYP',
 'FINANZTYP',
 'LP_FAMILIE_FEIN',
 'CAMEO_DEU_2015',
 'CAMEO_DEUG_2015',
 'LP_FAMILIE_GROB',
 'GFK_URLAUBERTYP',
 'NATIONALITAET_KZ',
 'LP_STATUS_GROB',
 'GEBAEUDETYP']
In [39]:
azdias_below_trsh.shape
Out[39]:
(797961, 79)
In [40]:
# Drop the multi-level categoricals
azdias_below_trsh = azdias_below_trsh.drop(drop_cat_feats, axis=1)
In [41]:
# Re-encode the categorical variable with non-numeric values, namely, the "OST_WEST_KZ" feature
azdias_below_trsh['OST_WEST_KZ'] = azdias_below_trsh['OST_WEST_KZ'].map({'O':0, 'W':1})
In [42]:
azdias_below_trsh.OST_WEST_KZ.value_counts()
Out[42]:
1    629433
0    168528
Name: OST_WEST_KZ, dtype: int64

Discussion 1.2.1: Re-Encode Categorical Features

I have kept the binary categorical features and dropped the multi-level categorical variables (with three or more values). Among the five binary categorical variables all but one have numeric values, so I kept those as they are. For the one binary categorical variable with non-numeric values (OST_WEST_KZ), I re-encoded it numerically as 0 ("O") and 1 ("W").

Step 1.2.2: Engineer Mixed-Type Features

There are a handful of features that are marked as "mixed" in the feature summary that require special treatment in order to be included in the analysis. There are two in particular that deserve attention; the handling of the rest are up to your own choices:

  • "PRAEGENDE_JUGENDJAHRE" combines information on three dimensions: generation by decade, movement (mainstream vs. avantgarde), and nation (east vs. west). While there aren't enough levels to disentangle east from west, you should create two new variables to capture the other two dimensions: an interval-type variable for decade, and a binary variable for movement.
  • "CAMEO_INTL_2015" combines information on two axes: wealth and life stage. Break up the two-digit codes by their 'tens'-place and 'ones'-place digits into two new ordinal variables (which, for the purposes of this project, is equivalent to just treating them as their raw numeric values).
  • If you decide to keep or engineer new features around the other mixed-type features, make sure you note your steps in the Discussion section.

Be sure to check Data_Dictionary.md for the details needed to finish these tasks.

In [43]:
feat_info[feat_info.type=='mixed']
Out[43]:
attribute information_level type missing_or_unknown
15 LP_LEBENSPHASE_FEIN person mixed [0]
16 LP_LEBENSPHASE_GROB person mixed [0]
22 PRAEGENDE_JUGENDJAHRE person mixed [-1,0]
56 WOHNLAGE building mixed [-1]
59 CAMEO_INTL_2015 microcell_rr4 mixed [-1,XX]
64 KBA05_BAUMAX microcell_rr3 mixed [-1,0]
79 PLZ8_BAUMAX macrocell_plz8 mixed [-1,0]
In [44]:
# Investigate "PRAEGENDE_JUGENDJAHRE" and engineer two new variables.
azdias_below_trsh.PRAEGENDE_JUGENDJAHRE.unique()

# generation -- by decade, and movement -- mainstream vs avantgrade
Out[44]:
array([ 14.,  15.,   8.,   3.,  10.,  11.,   5.,   9.,   6.,   4.,  nan,
         2.,   1.,  12.,  13.,   7.])
In [45]:
def genr(x):
    """
    A function that captures generation (by decade) out of the PRAEGENDE_JUGENDJAHRE feature     
    INPUT: 
        the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
    OUTPUT: 
        the decade of the feature (40 for 40s, 50 for 50s, etc.)
    """
    if x is np.nan:
        return np.nan
    elif x in list(map(float, [1,2])):
        return 40
    elif x in list(map(float, [3,4])):
        return 50
    elif x in list(map(float, [5,6,7])):
        return 60
    elif x in list(map(float, [8,9])):
        return 70
    elif x in list(map(float, [10,11,12,13])):
        return 80
    elif x in list(map(float, [14,15])):
        return 90
    
def movement(x):
    """
    A function that captures MOVEMENT (mainstream vs. avantgarde) out of the PRAEGENDE_JUGENDJAHRE feature 
    Arg: 
        the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
    Returns: 
        binary values (0 for 'Mainstream' and 1 for 'Avantgarde')
    """
    if x is np.nan:
        return np.nan
    elif x in list(map(float, [1,3,5,8,10,12,14])):
        return 0
    elif x in list(map(float, [2,4,6,7,9,11,13,15])):
        return 1
In [46]:
azdias_below_trsh['GENERATION']=azdias_below_trsh.PRAEGENDE_JUGENDJAHRE.map(genr)
azdias_below_trsh['MOVEMENT']=azdias_below_trsh.PRAEGENDE_JUGENDJAHRE.map(movement)
In [47]:
# Investigate "CAMEO_INTL_2015" and engineer two new variables.
azdias_below_trsh.CAMEO_INTL_2015.unique()

# wealth -- tens-place digit, life_stage -- ones-place digit
Out[47]:
array(['51', '24', '12', '43', '54', '22', '14', '13', '15', '33', '41',
       '34', '55', nan, '25', '23', '31', '52', '35', '45', '44', '32'], dtype=object)
In [48]:
azdias_below_trsh.CAMEO_INTL_2015.isnull().sum()
Out[48]:
6121
In [49]:
def tens_digit(x):
    if x is np.nan:
        return np.nan
    else:
        return int(x[0])

def ones_digit(x):
    if x is np.nan:
        return np.nan
    else:
        return int(x[1])
    
In [50]:
azdias_below_trsh['WEALTH']=azdias_below_trsh.CAMEO_INTL_2015.map(tens_digit)
azdias_below_trsh['LIFE_STAGE']=azdias_below_trsh.CAMEO_INTL_2015.map(ones_digit)
In [51]:
mixed_feats = list(feat_info[feat_info.type=='mixed'].attribute.values)
mixed_feats = list(set(mixed_feats) - set(remove_feats))
mixed_feats
Out[51]:
['PLZ8_BAUMAX',
 'LP_LEBENSPHASE_GROB',
 'LP_LEBENSPHASE_FEIN',
 'CAMEO_INTL_2015',
 'PRAEGENDE_JUGENDJAHRE',
 'WOHNLAGE']
In [52]:
# Drop the mixed features from the one_hot_data including PRAEGENDE_JUGENDJAHRE and CAMEO_INTL_2015

azdias_below_trsh = azdias_below_trsh.drop(mixed_feats, axis=1)

Discussion 1.2.2: Engineer Mixed-Type Features

With regards to the mixed-value features, I created two variables ("GENERATION" and "MOVEMENT") from the "PRAEGENDE_JUGENDJAHRE" feature using the genr and movement functions I wrote above. Similarly, I created two variables ("WEALTH" and "LIFE_STAGE") from the "CAMEO_INTL_2015" mixed-value feature using the tens_digit and ones_digit functions I wrote above that split the tens digit and ones digit of a two-digit number. Finally, I dropped all the mixed-value features including "PRAEGENDE_JUGENDJAHRE" and "CAMEO_INTL_2015" (after I derived the new variables mentioned above from them). The reason for dropping all mixed-value features was just for simplicity - some of the mixed features are fine-scale classifications and hence, have several possible values. Referencing the Data_Dictionary.md document was crucial for this step, particularly, in understanding the dimensions of the "PRAEGENDE_JUGENDJAHRE" and "CAMEO_INTL_2015" features, and it enabled me to write the genr and movement functions above.

Step 1.2.3: Complete Feature Selection

In order to finish this step up, you need to make sure that your data frame now only has the columns that you want to keep. To summarize, the dataframe should consist of the following:

  • All numeric, interval, and ordinal type columns from the original dataset.
  • Binary categorical features (all numerically-encoded).
  • Engineered features from other multi-level categorical features and mixed features.

Make sure that for any new columns that you have engineered, that you've excluded the original columns from the final dataset. Otherwise, their values will interfere with the analysis later on the project. For example, you should not keep "PRAEGENDE_JUGENDJAHRE", since its values won't be useful for the algorithm: only the values derived from it in the engineered features you created should be retained. As a reminder, your data should only be from the subset with few or no missing values.

In [53]:
# If there are other re-engineering tasks you need to perform, make sure you
# take care of them here. (Dealing with missing data will come in step 2.1.)

azdias_below_trsh.shape
Out[53]:
(797961, 64)
In [54]:
# Do whatever you need to in order to ensure that the dataframe only contains
# the columns that should be passed to the algorithm functions.
azdias_below_trsh.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 797961 entries, 1 to 891220
Data columns (total 64 columns):
ALTERSKATEGORIE_GROB     795160 non-null float64
ANREDE_KZ                797961 non-null int64
FINANZ_MINIMALIST        797961 non-null int64
FINANZ_SPARER            797961 non-null int64
FINANZ_VORSORGER         797961 non-null int64
FINANZ_ANLEGER           797961 non-null int64
FINANZ_UNAUFFAELLIGER    797961 non-null int64
FINANZ_HAUSBAUER         797961 non-null int64
GREEN_AVANTGARDE         797961 non-null int64
HEALTH_TYP               761281 non-null float64
RETOURTYP_BK_S           793248 non-null float64
SEMIO_SOZ                797961 non-null int64
SEMIO_FAM                797961 non-null int64
SEMIO_REL                797961 non-null int64
SEMIO_MAT                797961 non-null int64
SEMIO_VERT               797961 non-null int64
SEMIO_LUST               797961 non-null int64
SEMIO_ERL                797961 non-null int64
SEMIO_KULT               797961 non-null int64
SEMIO_RAT                797961 non-null int64
SEMIO_KRIT               797961 non-null int64
SEMIO_DOM                797961 non-null int64
SEMIO_KAEM               797961 non-null int64
SEMIO_PFLICHT            797961 non-null int64
SEMIO_TRADV              797961 non-null int64
SOHO_KZ                  797961 non-null float64
VERS_TYP                 761281 non-null float64
ANZ_PERSONEN             797961 non-null float64
ANZ_TITEL                797961 non-null float64
HH_EINKOMMEN_SCORE       797961 non-null float64
W_KEIT_KIND_HH           738718 non-null float64
WOHNDAUER_2008           797961 non-null float64
ANZ_HAUSHALTE_AKTIV      791535 non-null float64
ANZ_HH_TITEL             794138 non-null float64
KONSUMNAEHE              797891 non-null float64
MIN_GEBAEUDEJAHR         797961 non-null float64
OST_WEST_KZ              797961 non-null int64
KBA05_ANTG1              757897 non-null float64
KBA05_ANTG2              757897 non-null float64
KBA05_ANTG3              757897 non-null float64
KBA05_ANTG4              757897 non-null float64
KBA05_GBZ                757897 non-null float64
BALLRAUM                 797369 non-null float64
EWDICHTE                 797369 non-null float64
INNENSTADT               797369 non-null float64
GEBAEUDETYP_RASTER       797954 non-null float64
KKK                      733146 non-null float64
MOBI_REGIO               757897 non-null float64
ONLINE_AFFINITAET        793248 non-null float64
REGIOTYP                 733146 non-null float64
KBA13_ANZAHL_PKW         785412 non-null float64
PLZ8_ANTG1               774706 non-null float64
PLZ8_ANTG2               774706 non-null float64
PLZ8_ANTG3               774706 non-null float64
PLZ8_ANTG4               774706 non-null float64
PLZ8_HHZ                 774706 non-null float64
PLZ8_GBZ                 774706 non-null float64
ARBEIT                   793734 non-null float64
ORTSGR_KLS9              793835 non-null float64
RELAT_AB                 793734 non-null float64
GENERATION               769252 non-null float64
MOVEMENT                 769252 non-null float64
WEALTH                   791840 non-null float64
LIFE_STAGE               791840 non-null float64
dtypes: float64(41), int64(23)
memory usage: 415.7 MB

Step 1.3: Create a Cleaning Function

Even though you've finished cleaning up the general population demographics data, it's important to look ahead to the future and realize that you'll need to perform the same cleaning steps on the customer demographics data. In this substep, complete the function below to execute the main feature selection, encoding, and re-engineering steps you performed above. Then, when it comes to looking at the customer data in Step 3, you can just run this function on that DataFrame to get the trimmed dataset in a single step.

In [55]:
# Load in the general demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';')
In [56]:
customers.shape
Out[56]:
(191652, 85)
In [57]:
customers.head()
Out[57]:
AGER_TYP ALTERSKATEGORIE_GROB ANREDE_KZ CJT_GESAMTTYP FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER ... PLZ8_ANTG1 PLZ8_ANTG2 PLZ8_ANTG3 PLZ8_ANTG4 PLZ8_BAUMAX PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB
0 2 4 1 5.0 5 1 5 1 2 2 ... 3.0 3.0 1.0 0.0 1.0 5.0 5.0 1.0 2.0 1.0
1 -1 4 1 NaN 5 1 5 1 3 2 ... NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
2 -1 4 2 2.0 5 1 5 1 4 4 ... 2.0 3.0 3.0 1.0 3.0 3.0 2.0 3.0 5.0 3.0
3 1 4 1 2.0 5 1 5 2 1 2 ... 3.0 2.0 1.0 0.0 1.0 3.0 4.0 1.0 3.0 1.0
4 -1 3 1 6.0 3 1 4 4 5 2 ... 2.0 4.0 2.0 1.0 2.0 3.0 3.0 3.0 5.0 1.0

5 rows × 85 columns

In [58]:
# Histogram of the total missing vlaues in each feature
customers.isnull().sum().sort_values().hist(bins=25);
In [59]:
# Histogram of the total missing values in each row
customers.isnull().sum(axis=1).sort_values().hist();
In [60]:
# Missing values by features
plt.figure(figsize=(12,20))
customers.isnull().sum().sort_values().plot(kind='barh');

Cleaning function and some helper functions

In [61]:
import re

def convert_missing_unknown_to_nan(df, features=feat_info):
    """
    Identify missing or unknown data values in the DataFrame df and convert them to NaN.
    INPUT: 
        DataFrames df and features
    OUTPUT: 
        cleaned DataFrame
    """
    unknown_or_missing_vals = list(set(features.missing_or_unknown.unique()) - set(['[]']))
    #print(unknown_or_missing_vals)
    regex = re.compile(r'[-]?\d|[X]+')
    for val in unknown_or_missing_vals:
        if val == '[XX]':
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace(['XX'], np.nan)

        elif val == '[-1,X]':
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace([-1, 'X'], np.nan)

        elif val == '[-1,XX]':
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace([-1, 'XX'], np.nan)

        else:
            unknown_num_vals = regex.findall(val)
            unknown_num_vals = list(map(int, unknown_num_vals))
            feature_to_clean = features[features.missing_or_unknown == val].attribute.values 
            df[feature_to_clean] = df[feature_to_clean].replace(unknown_num_vals, np.nan)
            
    return df
            

def genr(x):
    """
    A function that captures generation (by decade) out of the PRAEGENDE_JUGENDJAHRE feature     
    INPUT: 
        the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
    OUTPUT: 
        the decade of the feature (40 for 40s, 50 for 50s, etc.)
    """
    if x is np.nan:
        return np.nan
    elif x in list(map(float, [1,2])):
        return 40
    elif x in list(map(float, [3,4])):
        return 50
    elif x in list(map(float, [5,6,7])):
        return 60
    elif x in list(map(float, [8,9])):
        return 70
    elif x in list(map(float, [10,11,12,13])):
        return 80
    elif x in list(map(float, [14,15])):
        return 90
    
def movement(x):
    """
    A function that captures MOVEMENT (mainstream vs. avantgarde) out of the PRAEGENDE_JUGENDJAHRE feature 
    INPUT: 
        the encoding of the PRAEGENDE_JUGENDJAHRE feature (a number between 1 and 15)
    OUTPUT: 
        binary values (0 for 'Mainstream' and 1 for 'Avantgarde')
    """
    if x is np.nan:
        return np.nan
    elif x in list(map(float, [1,3,5,8,10,12,14])):
        return 0
    elif x in list(map(float, [2,4,6,7,9,11,13,15])):
        return 1


def tens_digit(x):
    """A function that splits a two digit number and returns the tens place digit"""
    if x is np.nan:
        return np.nan
    else:
        return int(x[0])

def ones_digit(x):
    """A function that splits a two digit number and returns the ones place digit"""
    if x is np.nan:
        return np.nan
    else:
        return int(x[1])
    
    
def clean_data(df, features=feat_info):
    """
    Perform feature trimming, re-encoding, and engineering for demographics data
    
    INPUT: Demographics DataFrame
    OUTPUT: Trimmed and cleaned demographics DataFrame
    """
    
    # Put in code here to execute all main cleaning steps:
    # convert missing value codes into NaNs, ...
    df = convert_missing_unknown_to_nan(df)
        
    # Remove selected columns and rows, ...
    remove_feats = ['AGER_TYP','GEBURTSJAHR','TITEL_KZ','ALTER_HH','KK_KUNDENTYP','KBA05_BAUMAX']
    df.drop(remove_feats, axis=1, inplace=True)
    
    # Separate observations with missing values above and below a fixed threshold
    ind_below_trsh = df.isnull().sum(axis=1).values <=25
    df_below_trsh = df.iloc[ind_below_trsh]
    df_above_trsh = df.iloc[~ind_below_trsh]
    
    # Select, re-encode, and engineer column values.
    cat_feats = list(set(features[features.type == 'categorical'].attribute.values )-set(remove_feats))
    df_cat = df_below_trsh[cat_feats]
    retain_cat_feats = list(df_cat.nunique()[df_cat.nunique().values < 3].keys())
    drop_cat_feats = list(set(cat_feats) - set(retain_cat_feats))
    
    df_below_trsh = df_below_trsh.drop(drop_cat_feats, axis=1)
    
    df_below_trsh['OST_WEST_KZ'] = df_below_trsh['OST_WEST_KZ'].map({'O':0, 'W':1})
    
    df_below_trsh['GENERATION']=df_below_trsh.PRAEGENDE_JUGENDJAHRE.map(genr)
    df_below_trsh['MOVEMENT']=df_below_trsh.PRAEGENDE_JUGENDJAHRE.map(movement)
    df_below_trsh['WEALTH']=df_below_trsh.CAMEO_INTL_2015.map(tens_digit)
    df_below_trsh['LIFE_STAGE']=df_below_trsh.CAMEO_INTL_2015.map(ones_digit)
    
    mixed_feats = list(features[features.type=='mixed'].attribute.values)
    mixed_feats = list(set(mixed_feats) - set(remove_feats))
    df_below_trsh = df_below_trsh.drop(mixed_feats, axis=1)
    
    # Return the cleaned dataframe.
    return df_below_trsh
    

Step 2: Feature Transformation

Step 2.1: Apply Feature Scaling

Before we apply dimensionality reduction techniques to the data, we need to perform feature scaling so that the principal component vectors are not influenced by the natural differences in scale for features. Starting from this part of the project, you'll want to keep an eye on the API reference page for sklearn to help you navigate to all of the classes and functions that you'll need. In this substep, you'll need to check the following:

  • sklearn requires that data not have missing values in order for its estimators to work properly. So, before applying the scaler to your data, make sure that you've cleaned the DataFrame of the remaining missing values. This can be as simple as just removing all data points with missing data, or applying an Imputer to replace all missing values. You might also try a more complicated procedure where you temporarily remove missing values in order to compute the scaling parameters before re-introducing those missing values and applying imputation. Think about how much missing data you have and what possible effects each approach might have on your analysis, and justify your decision in the discussion section below.
  • For the actual scaling function, a StandardScaler instance is suggested, scaling each feature to mean 0 and standard deviation 1.
  • For these classes, you can make use of the .fit_transform() method to both fit a procedure to the data as well as apply the transformation to the data at the same time. Don't forget to keep the fit sklearn objects handy, since you'll be applying them to the customer demographics data towards the end of the project.
In [62]:
# If you've not yet cleaned the dataset of all NaN values, then investigate and
# do that now.


display((azdias_below_trsh.isnull().sum()==0).mean())

display((azdias_below_trsh.isnull().sum(axis=1)==0).mean())
0.453125
0.78100433479831721
In [63]:
# Drop all rows with missing values
azdias_below_trsh.dropna(axis=0, how='any', inplace=True)
In [64]:
azdias_below_trsh.shape
Out[64]:
(623211, 64)
In [65]:
azdias_below_trsh.head()
Out[65]:
ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE HEALTH_TYP ... PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB GENERATION MOVEMENT WEALTH LIFE_STAGE
1 1.0 2 1 5 2 5 4 5 0 3.0 ... 1.0 5.0 4.0 3.0 5.0 4.0 90.0 0.0 5.0 1.0
2 3.0 2 1 4 1 2 3 5 1 3.0 ... 0.0 4.0 4.0 3.0 5.0 2.0 90.0 1.0 2.0 4.0
4 3.0 1 4 3 4 1 3 2 0 3.0 ... 1.0 3.0 3.0 4.0 6.0 5.0 70.0 0.0 4.0 3.0
5 1.0 2 3 1 5 2 2 5 0 3.0 ... 1.0 5.0 5.0 2.0 3.0 3.0 50.0 0.0 5.0 4.0
6 2.0 2 1 5 1 5 4 3 0 2.0 ... 0.0 5.0 5.0 4.0 6.0 3.0 80.0 0.0 2.0 2.0

5 rows × 64 columns

In [66]:
# Apply feature scaling to the general population demographics data.

from sklearn.preprocessing import StandardScaler

X = StandardScaler().fit_transform(azdias_below_trsh)
In [67]:
X
Out[67]:
array([[-1.74628678,  0.97782483, -1.51222588, ..., -0.55367151,
         1.14788447, -1.25111082],
       [ 0.202108  ,  0.97782483, -1.51222588, ...,  1.80612507,
        -0.90999235,  0.74981994],
       [ 0.202108  , -1.02267806,  0.6924003 , ..., -0.55367151,
         0.46192553,  0.08284302],
       ..., 
       [-0.77208939,  0.97782483, -1.51222588, ..., -0.55367151,
        -0.22403341, -1.25111082],
       [-1.74628678, -1.02267806, -1.51222588, ..., -0.55367151,
         1.14788447, -1.25111082],
       [ 1.17630539, -1.02267806,  0.6924003 , ..., -0.55367151,
         0.46192553,  0.08284302]])

Discussion 2.1: Apply Feature Scaling

I removed all rows with any missing values and then I used the fit_transform method of StandardScaler function.

Step 2.2: Perform Dimensionality Reduction

On your scaled data, you are now ready to apply dimensionality reduction techniques.

  • Use sklearn's PCA class to apply principal component analysis on the data, thus finding the vectors of maximal variance in the data. To start, you should not set any parameters (so all components are computed) or set a number of components that is at least half the number of features (so there's enough features to see the general trend in variability).
  • Check out the ratio of variance explained by each principal component as well as the cumulative variance explained. Try plotting the cumulative or sequential values using matplotlib's plot() function. Based on what you find, select a value for the number of transformed features you'll retain for the clustering part of the project.
  • Once you've made a choice for the number of components to keep, make sure you re-fit a PCA instance to perform the decided-on transformation.
In [68]:
# Apply PCA to the data.

from sklearn.decomposition import PCA

pca = PCA()

X_pca = pca.fit_transform(X)
In [69]:
# Investigate the variance accounted for by each principal component.

from functools import partial

round_3 = partial(round, ndigits=3)

np.array(list(map(round_3, pca.explained_variance_ratio_))) 
Out[69]:
array([ 0.174,  0.137,  0.096,  0.054,  0.038,  0.032,  0.028,  0.025,
        0.024,  0.021,  0.02 ,  0.019,  0.018,  0.017,  0.016,  0.016,
        0.015,  0.014,  0.013,  0.013,  0.013,  0.012,  0.012,  0.011,
        0.011,  0.009,  0.008,  0.008,  0.007,  0.007,  0.007,  0.007,
        0.006,  0.006,  0.006,  0.006,  0.005,  0.005,  0.005,  0.004,
        0.004,  0.004,  0.004,  0.004,  0.003,  0.003,  0.003,  0.003,
        0.003,  0.003,  0.003,  0.002,  0.002,  0.002,  0.002,  0.002,
        0.002,  0.002,  0.002,  0.001,  0.001,  0.001,  0.001,  0.   ])
In [70]:
def scree_plot(pca):
    '''
    Creates a scree plot associated with the principal components

    INPUT: pca - the result of instantian of PCA in scikit learn

    OUTPUT: None
    '''
    num_components=len(pca.explained_variance_ratio_)
    ind = np.arange(num_components)
    vals = pca.explained_variance_ratio_
    cumvals = np.cumsum(vals)
    
    plt.figure(figsize=(20, 10))
    
    ax = plt.subplot(111)    
    ax.bar(ind, vals)
    ax.scatter(ind, cumvals, zorder=3)
    ax.plot(ind, cumvals, ls=':', color='orange')
    for i in range(num_components):
        ax.annotate("{:.2f}%".format(vals[i]*100), (ind[i]+0.8, vals[i]), 
        va='bottom', ha="center", rotation=45, fontsize=10)
    for i in range(1, num_components):
        ax.annotate(r"%s%%" % ((str(cumvals[i]*100)[:4])), (ind[i], cumvals[i] - 0.02), 
        ha="left", rotation=-45, fontsize=12, color='gray')

    ax.xaxis.set_tick_params(width=0)
    ax.yaxis.set_tick_params(width=2, length=8)

    ax.set_xlabel("Principal Component")
    ax.set_ylabel("Variance Explained (%)")
    plt.title('Explained Variance Per Principal Component')
    
    plt.grid(b=True, linewidth=0.5)
In [71]:
scree_plot(pca)
In [72]:
# Re-apply PCA to the data while selecting for number of components to retain.

for ncomp in range(37, 45):
    pca = PCA(ncomp)
    X_pca = pca.fit_transform(X)
    vals = pca.explained_variance_ratio_
    cumvals = np.cumsum(vals)
    if cumvals[-1] > .95:
        print("{:.2f}% of the variance can be explained with only {} components.".format(cumvals[-1]*100, ncomp))
        break
95.09% of the variance can be explained with only 42 components.

Discussion 2.2: Perform Dimensionality Reduction

About 95% of the variance can be explained with only 42 components. So, I am going to retain 42 principal components in the next step.

Step 2.3: Interpret Principal Components

Now that we have our transformed principal components, it's a nice idea to check out the weight of each variable on the first few components to see if they can be interpreted in some fashion.

As a reminder, each principal component is a unit vector that points in the direction of highest variance (after accounting for the variance captured by earlier principal components). The further a weight is from zero, the more the principal component is in the direction of the corresponding feature. If two features have large weights of the same sign (both positive or both negative), then increases in one tend to be associated with increases in the other. To contrast, features with different signs can be expected to show a negative correlation: increases in one variable should result in a decrease in the other.

  • To investigate the features, you should map each weight to their corresponding feature name, then sort the features according to weight. The most interesting features for each principal component, then, will be those at the beginning and end of the sorted list. Use the data dictionary document to help you understand these most prominent features, their relationships, and what a positive or negative value on the principal component might indicate.
  • You should investigate and interpret feature associations from the first three principal components in this substep. To help facilitate this, you should write a function that you can call at any time to print the sorted list of feature weights, for the i-th principal component. This might come in handy in the next step of the project, when you interpret the tendencies of the discovered clusters.
In [73]:
pca.components_.shape
Out[73]:
(42, 64)
In [74]:
pca.components_
Out[74]:
array([[-0.14790436, -0.00388173, -0.22248391, ..., -0.11530134,
         0.19715556, -0.12597656],
       [ 0.24518741,  0.09021503,  0.04081492, ..., -0.03086245,
         0.0927012 , -0.01705119],
       [ 0.08235406, -0.36763513,  0.15666982, ...,  0.05085065,
         0.02485282, -0.00934211],
       ..., 
       [-0.05549455,  0.12277948,  0.05772123, ..., -0.00629162,
        -0.00604727,  0.01970659],
       [ 0.02734884, -0.02559099, -0.01364094, ...,  0.05941397,
        -0.30668345, -0.05108691],
       [ 0.0322869 , -0.02081372, -0.0429907 , ...,  0.04523493,
        -0.10169259, -0.02310192]])
In [75]:
# Construct a dataframe by mapping weights for the principal components to corresponding feature names
pca_result = pd.DataFrame(pca.components_, index=['Dimension_{}'.format(num) for num in range(1, len(pca.components_)+1)],
                         columns=azdias_below_trsh.columns)
pca_result['Explained-Variance'] = pca.explained_variance_ratio_
pca_result = pca_result[['Explained-Variance'] + list(azdias_below_trsh.columns)]
In [76]:
pca_result.head()
Out[76]:
Explained-Variance ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE ... PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB GENERATION MOVEMENT WEALTH LIFE_STAGE
Dimension_1 0.174123 -0.147904 -0.003882 -0.222484 0.165815 -0.136351 0.087292 0.094742 0.144909 -0.115301 ... 0.207551 0.035649 -0.162744 0.137236 0.184226 0.124980 0.126726 -0.115301 0.197156 -0.125977
Dimension_2 0.136980 0.245187 0.090215 0.040815 -0.217398 0.213828 -0.193506 -0.216888 0.130939 -0.030862 ... 0.112918 0.014866 -0.092383 0.083185 0.110599 0.077828 -0.236761 -0.030862 0.092701 -0.017051
Dimension_3 0.096434 0.082354 -0.367635 0.156670 -0.101300 0.098247 -0.188284 -0.092779 -0.047402 0.050851 ... 0.046401 0.006607 -0.037479 0.033020 0.048823 0.031362 -0.107608 0.050851 0.024853 -0.009342
Dimension_4 0.053618 -0.042267 0.042771 0.058340 -0.000438 -0.019887 -0.128428 0.088772 -0.101835 0.391572 ... 0.085562 0.129155 0.022814 0.050947 0.250306 0.093386 0.040798 0.391572 -0.130830 0.061196
Dimension_5 0.037548 -0.002339 -0.006189 -0.083350 -0.000054 0.059678 -0.048852 0.042764 0.086203 -0.057644 ... -0.015629 0.495551 0.397791 -0.206553 -0.089270 -0.139497 -0.032315 -0.057644 0.007773 -0.027239

5 rows × 65 columns

In [77]:
# Each principal component is a unit vector

for i in range(len(pca.components_)):
    norm_i = np.dot(pca_result.iloc[i][1:], pca_result.iloc[i][1:])
    assert (norm_i-1.0) < 1e-14
In [78]:
# Map weights for a specified principal component to corresponding feature names
# and then print the linked values, sorted by weight.
# HINT: Try defining a function here or in a new cell that you can reuse in the
# other cells.
def color_code(x):
    if x:
        return '#3498db'
    return '#e74c3c'


def sorted_feature_weights(n_comp=1):
    """
    Maps weights for a specified principal component to corresponding feature names
    and then generates a bar-plot of the linked values, sorted by weight.
    """
    if n_comp < 1 or n_comp > pca_result.shape[0]:
        print('Enter a valid component number (between 1 and {}.)'.format(pca_result.shape[0]))
    else:
        vect = pd.DataFrame(pca_result.iloc[n_comp - 1][1:].sort_values())
        vect['Positive'] = vect[vect.columns[0]] > 0.0
        ind = range(vect.shape[0])
        plt.figure(figsize=(10,20))
        ax = plt.barh(ind, vect[vect.columns[0]], color=vect.Positive.map(color_code), alpha=0.8)
        plt.yticks(ind, vect.index)
    
In [79]:
sorted_feature_weights(1)
In [80]:
# Map weights for the second principal component to corresponding feature names
# and then print the linked values, sorted by weight.

sorted_feature_weights(2)
In [81]:
# Map weights for the third principal component to corresponding feature names
# and then print the linked values, sorted by weight.

sorted_feature_weights(3)

Discussion 2.3: Interpret Principal Components

I think the above plots of the weights of the features in the principal components are very informative. For example, for the first principal component, the major features with larger positive weights are associated with the number of larger family houses in the region, wealth, estimated household net income, size of the community, density of households per square kilometer, and money saving habits, in that order. On the other hand, the major features with larger negative weights for the first principal component are associated with movement patterns, low financial interests, number of smaller family houses in the region, distance from building to point of sale, and distance to city center.

For the second principal component the major features that contribute positively include: estimated age, event-orientedness, financial preparedness, sensual-mindedness, return type, and homeownership. On the other hand, the features that contribute negatively include: being religious, generation, dutifulness, traditional-mindedness, financial inconspicuousness, and cultural-mindedness.

For the third principal component, the major features that contribute positively include: personal typology such as dreamfulness, social-mindedness, family-mindedness, cultural-mindedness, low financial interest, return type. On the other hand, the features that contribute negatively include: gender, combative attitude, dominant-mindedness, critical-mindedness, being rational, and being an investor.

Step 3: Clustering

Step 3.1: Apply Clustering to General Population

You've assessed and cleaned the demographics data, then scaled and transformed them. Now, it's time to see how the data clusters in the principal components space. In this substep, you will apply k-means clustering to the dataset and use the average within-cluster distances from each point to their assigned cluster's centroid to decide on a number of clusters to keep.

  • Use sklearn's KMeans class to perform k-means clustering on the PCA-transformed data.
  • Then, compute the average difference from each point to its assigned cluster's center. Hint: The KMeans object's .score() method might be useful here, but note that in sklearn, scores tend to be defined so that larger is better. Try applying it to a small, toy dataset, or use an internet search to help your understanding.
  • Perform the above two steps for a number of different cluster counts. You can then see how the average distance decreases with an increasing number of clusters. However, each additional cluster provides a smaller net benefit. Use this fact to select a final number of clusters in which to group the data. Warning: because of the large size of the dataset, it can take a long time for the algorithm to resolve. The more clusters to fit, the longer the algorithm will take. You should test for cluster counts through at least 10 clusters to get the full picture, but you shouldn't need to test for a number of clusters above about 30.
  • Once you've selected a final number of clusters to use, re-fit a KMeans instance to perform the clustering operation. Make sure that you also obtain the cluster assignments for the general demographics data, since you'll be using them in the final Step 3.3.
In [82]:
# Over a number of different cluster counts...
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler


def plot_data(data, labels):
    '''
    Plot data with colors associated with labels
    '''
    fig = plt.figure(figsize=(10,10));
    ax = Axes3D(fig)
    ax.scatter(data[:,0], data[:,2], data[:,5], c=labels, cmap='tab10');


def get_kmeans_score(data, center):
    '''
    returns the kmeans score regarding SSE for points to centers
    INPUT:
        data - the dataset you want to fit kmeans to
        center - the number of centers you want (the k value)
    OUTPUT:
        score - the SSE score for the kmeans model fit to the data
    '''
    #instantiate kmeans
    kmeans = KMeans(n_clusters=center)
    # Then fit the model to your data using the fit method
    model = kmeans.fit(data)
    # Obtain a score related to the model fit
    score = np.abs(model.score(data))
    return score

def fit_mods(data):
    scores = []
    centers = list(range(1,11))
    for center in centers:
        scores.append(get_kmeans_score(data, center))
    return centers, scores

def plot_sse_vs_k(centers, scores):
    """
    Generates a line plot of SSE (scores) vs. K (number of centers)
    INPUT: centers, scores
    OUTPUT: none
    """
    plt.figure(figsize=(12,6))
    plt.plot(centers, scores, linestyle='--', marker='o');
    plt.xlabel('K');
    plt.ylabel('SSE');
    plt.title('SSE vs. K');  
In [83]:
X = StandardScaler().fit_transform(azdias_below_trsh)
pca = PCA(42)
X_pca = pca.fit_transform(X)
In [84]:
# run k-means clustering on the data with n_clusters = 4
kmeans_4 = KMeans(n_clusters = 4)
model_4 = kmeans_4.fit(X_pca)
labels_4 = model_4.predict(X_pca)
plot_data(X_pca, labels_4)
In [85]:
data = X_pca

# compute the average within-cluster distances.
centers, scores = fit_mods(data)

# Investigate the change in within-cluster distance across number of clusters.
# HINT: Use matplotlib's plot function to visualize this relationship.
plot_sse_vs_k(centers, scores)
In [86]:
# Re-fit the k-means model with the selected number of clusters and obtain
# cluster predictions for the general population demographics data.

kmeans_3 = KMeans(n_clusters=3)
model_3 = kmeans_3.fit(X_pca)
labels_3 = model_3.predict(X_pca)
plot_data(X_pca, labels_3)

Discussion 3.1: Apply Clustering to General Population

The SSE score vs K plot above shows that the decreases in SSE scores as K increases from 1 to 2 and from 2 to 3 are relatively subtantial, whereas from K=3 onwards, we only see a very gradual decrease in the SSE score. For this reason, I have decided to segment the population into three clusters.

Step 3.2: Apply All Steps to the Customer Data

Now that you have clusters and cluster centers for the general population, it's time to see how the customer data maps on to those clusters. Take care to not confuse this for re-fitting all of the models to the customer data. Instead, you're going to use the fits from the general population to clean, transform, and cluster the customer data. In the last step of the project, you will interpret how the general population fits apply to the customer data.

  • Don't forget when loading in the customers data, that it is semicolon (;) delimited.
  • Apply the same feature wrangling, selection, and engineering steps to the customer demographics using the clean_data() function you created earlier. (You can assume that the customer demographics data has similar meaning behind missing data patterns as the general demographics data.)
  • Use the sklearn objects from the general demographics data, and apply their transformations to the customers data. That is, you should not be using a .fit() or .fit_transform() method to re-fit the old objects, nor should you be creating new sklearn objects! Carry the data through the feature scaling, PCA, and clustering steps, obtaining cluster assignments for all of the data in the customer demographics data.
In [87]:
# Load in the customer demographics data.
customers = pd.read_csv('Udacity_CUSTOMERS_Subset.csv', delimiter=';')
In [88]:
customers.shape
Out[88]:
(191652, 85)

Apply preprocessing, feature transformation, and clustering from the general demographics onto the customer data, obtaining cluster predictions for the customer demographics data.

In [89]:
customers_clean = clean_data(customers)

customers_clean.shape
Out[89]:
(141713, 64)
In [90]:
customers_clean.isnull().sum().sum()
Out[90]:
104131
In [91]:
# Remove all rows with any missing values
customers_clean.dropna(axis=0, how='any', inplace=True)
In [92]:
customers_clean.shape
Out[92]:
(115643, 64)
In [93]:
scaler = StandardScaler().fit(azdias_below_trsh)
X = scaler.transform(azdias_below_trsh)

pca = PCA(42)
pca.fit(X)
X_pca = pca.transform(X)

kmeans = KMeans(3)
model = kmeans.fit(X_pca)
labels_gen = model.predict(X_pca)

X_customer = scaler.transform(customers_clean)
X_customer_pca = pca.transform(X_customer)
labels_cust = model.predict(X_customer_pca)

plot_data(X_customer_pca, labels_cust)

Step 3.3: Compare Customer Data to Demographics Data

At this point, you have clustered data based on demographics of the general population of Germany, and seen how the customer data for a mail-order sales company maps onto those demographic clusters. In this final substep, you will compare the two cluster distributions to see where the strongest customer base for the company is.

Consider the proportion of persons in each cluster for the general population, and the proportions for the customers. If we think the company's customer base to be universal, then the cluster assignment proportions should be fairly similar between the two. If there are only particular segments of the population that are interested in the company's products, then we should see a mismatch from one to the other. If there is a higher proportion of persons in a cluster for the customer data compared to the general population (e.g. 5% of persons are assigned to a cluster for the general population, but 15% of the customer data is closest to that cluster's centroid) then that suggests the people in that cluster to be a target audience for the company. On the other hand, the proportion of the data in a cluster being larger in the general population than the customer data (e.g. only 2% of customers closest to a population centroid that captures 6% of the data) suggests that group of persons to be outside of the target demographics.

Take a look at the following points in this step:

  • Compute the proportion of data points in each cluster for the general population and the customer data. Visualizations will be useful here: both for the individual dataset proportions, but also to visualize the ratios in cluster representation between groups. Seaborn's countplot() or barplot() function could be handy.
    • Recall the analysis you performed in step 1.1.3 of the project, where you separated out certain data points from the dataset if they had more than a specified threshold of missing values. If you found that this group was qualitatively different from the main bulk of the data, you should treat this as an additional data cluster in this analysis. Make sure that you account for the number of data points in this subset, for both the general population and customer datasets, when making your computations!
  • Which cluster or clusters are overrepresented in the customer dataset compared to the general population? Select at least one such cluster and infer what kind of people might be represented by that cluster. Use the principal component interpretations from step 2.3 or look at additional components to help you make this inference. Alternatively, you can use the .inverse_transform() method of the PCA and StandardScaler objects to transform centroids back to the original data space and interpret the retrieved values directly.
  • Perform a similar investigation for the underrepresented clusters. Which cluster or clusters are underrepresented in the customer dataset compared to the general population, and what kinds of people are typified by these clusters?
In [111]:
# Compare the proportion of data in each cluster for the customer data to the
# proportion of data in each cluster for the general population.

import seaborn as sns

plt.figure(figsize=(16,6))
plt.subplot(1,2,1)
ax=sns.countplot(labels_gen)

for i in range(3):
    # Note: azdias_below_trsh is about 89.5% of the general population, hence the multiplication by prop_below ~ 0.895
    plt.text(i,(labels_gen==i).sum()+1500,"{:.1f}%".format((labels_gen==i).mean()*100*prop_below))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title('Proportion of the General Population in Cluster',size=16)

plt.subplot(1,2,2)
ax=sns.countplot(labels_cust)
for i in range(3):
    plt.text(i,(labels_cust==i).sum()+1000,"{:.1f}%".format((labels_cust==i).mean()*100))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title('Proportion of Customers in Cluster',size=16);
In [112]:
# What kinds of people are part of a cluster that is overrepresented in the
# customer data compared to the general population?
# What kinds of people are part of a cluster that is underrepresented in the
# customer data compared to the general population?


def color_code(x):
    if x:
        return '#3498db'
    return '#e74c3c'


def plot_inv_transforms(centroid):
    """
    Applies the pca.inverse_transform() function to the kmeans cluster centers and
    plots the scaled coefficients of the features.
    """
    if centroid < 0 or centroid > 3:
        print('Enter a valid centroid (between 0 and 2 inclusive).')
    else:
        center = pca.inverse_transform(kmeans.cluster_centers_[centroid])

        features = pd.DataFrame(center, index=azdias_below_trsh.columns, columns=['scaled_coeffs'])
        features = features.sort_values(by='scaled_coeffs')
        
        features['Positive'] = features['scaled_coeffs'] > 0.0
        ind = range(len(features.index))
        plt.figure(figsize=(10,20))
        ax = plt.barh(ind, features['scaled_coeffs'], color=features.Positive.map(color_code), alpha=0.8)
        plt.yticks(ind, features.index)
        
In [113]:
plot_inv_transforms(0)
In [114]:
plot_inv_transforms(1)
In [115]:
plot_inv_transforms(2)

Discussion 3.3: Compare Customer Data to Demographics Data

The proportion of persons in each of the three clusters appear to be different between the general population and the cutomer base. The proportion of persons in the third cluster for each of the two groups is higher, but particularly over-represented in the customer base. Looking at the plots above of the scaled coefficients of the features obtained using pca.inverse_transform applied to the kmeans cluster centers indicate that these over-represented customer base include people characterized by: low financial interest, their movement patterns, number of smaller family houses in the area, and number of buildings in the area. On the other hand, persons in the first and second clusters are under represented in the customer base as compared to the general population, more so people that belong in the second cluster. From the first of the three bar-plots above, we can deduce that these people could be that can be characterized by their: dutifulness, traditional-mindedness, religiousness, and people that are money savers, among others.

Looking at the subset of the orginal dataset with a lot of missing values

In [122]:
def clean_data_v2(df, features=feat_info):
    """
    Perform feature trimming, re-encoding, and engineering for demographics data
    
    INPUT: Demographics DataFrame
    OUTPUT: Trimmed and cleaned demographics DataFrame
    """
    df_clean = df.copy()    
    # Remove selected columns and rows, ...
    remove_feats = ['AGER_TYP','GEBURTSJAHR','TITEL_KZ','ALTER_HH','KK_KUNDENTYP','KBA05_BAUMAX']
    
    # Select, re-encode, and engineer column values.
    cat_feats = list(set(features[features.type == 'categorical'].attribute.values )-set(remove_feats))
    df_cat = df_clean[cat_feats]
    retain_cat_feats = list(df_cat.nunique()[df_cat.nunique().values < 3].keys())
    drop_cat_feats = list(set(cat_feats) - set(retain_cat_feats))
    
    df_clean = df_clean.drop(drop_cat_feats, axis=1)
    
    df_clean['OST_WEST_KZ'] = df_clean['OST_WEST_KZ'].map({'O':0, 'W':1})
    
    df_clean['GENERATION']=df_clean.PRAEGENDE_JUGENDJAHRE.map(genr)
    df_clean['MOVEMENT']=df_clean.PRAEGENDE_JUGENDJAHRE.map(movement)
    df_clean['WEALTH']=df_clean.CAMEO_INTL_2015.map(tens_digit)
    df_clean['LIFE_STAGE']=df_clean.CAMEO_INTL_2015.map(ones_digit)
    
    mixed_feats = list(features[features.type=='mixed'].attribute.values)
    mixed_feats = list(set(mixed_feats) - set(remove_feats))
    df_clean = df_clean.drop(mixed_feats, axis=1)
    
    # Return the cleaned dataframe.
    return df_clean
In [123]:
azdias_above = clean_data_v2(azdias_above_trsh)
In [132]:
azdias_above[azdias_above.isnull().sum(axis=1) == 0]
Out[132]:
ALTERSKATEGORIE_GROB ANREDE_KZ FINANZ_MINIMALIST FINANZ_SPARER FINANZ_VORSORGER FINANZ_ANLEGER FINANZ_UNAUFFAELLIGER FINANZ_HAUSBAUER GREEN_AVANTGARDE HEALTH_TYP ... PLZ8_ANTG4 PLZ8_HHZ PLZ8_GBZ ARBEIT ORTSGR_KLS9 RELAT_AB GENERATION MOVEMENT WEALTH LIFE_STAGE

0 rows × 64 columns

Note: there are no rows in the azdias_above dataframe that don't have missing values. So, I will fill the missing ...

In [157]:
from sklearn.preprocessing import Imputer
In [145]:
azdias_above.shape
Out[145]:
(93260, 64)
In [162]:
selector = (azdias_above.isnull().sum().sort_values(ascending=False)==azdias_above.shape[0]).values
In [163]:
feats_all_nan = azdias_above.isnull().sum().sort_values(ascending=False).keys()[selector]
In [164]:
imp = Imputer(strategy='median')
azdias_above_fill = azdias_above.drop(feats_all_nan, axis=1)
azdias_above_fill_imp =imp.fit_transform(azdias_above_fill) 
In [166]:
scaler = StandardScaler().fit(azdias_above_fill_imp)
X = scaler.transform(azdias_above_fill_imp)

pca = PCA(42)
pca.fit(X)
X_pca = pca.transform(X)

kmeans = KMeans(1)
model = kmeans.fit(X_pca)
labels = model.predict(X_pca)
In [167]:
def color_code(x):
    if x:
        return '#3498db'
    return '#e74c3c'


def plot_inv_transform():
    """
    Applies the pca.inverse_transform() function to the kmeans cluster centers and
    plots the scaled coefficients of the features.
    """
    center = pca.inverse_transform(kmeans.cluster_centers_[0])

    features = pd.DataFrame(center, index=azdias_above_fill.columns, columns=['scaled_coeffs'])
    features = features.sort_values(by='scaled_coeffs')

    features['Positive'] = features['scaled_coeffs'] > 0.0
    ind = range(len(features.index))
    plt.figure(figsize=(10,20))
    ax = plt.barh(ind, features['scaled_coeffs'], color=features.Positive.map(color_code), alpha=0.8)
    plt.yticks(ind, features.index)
    
plot_inv_transform()

Remark: it appears that the people in the subset with a lot of missing values are those that can be characterized in terms of features that mainly include: first year building was mentioned in the database ("MIN_GEBAUEUDEJAHR"), neighborhood typology ("REGIOTYP"), and wealth.

Congratulations on making it this far in the project! Before you finish, make sure to check through the entire notebook from top to bottom to make sure that your analysis follows a logical flow and all of your findings are documented in Discussion cells. Once you've checked over all of your work, you should export the notebook as an HTML document to submit for evaluation. You can do this from the menu, navigating to File -> Download as -> HTML (.html). You will submit both that document and this notebook for your project submission.

In [ ]: